/*
 * Copyright 2007 by LongTop Corporation.
 * Softpack ChuangXin Building 15F, XiaMen, FuJian, PRC 361005
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * LongTop Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with LongTop.
 *
 */
package com.longtop.framework.security;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.longtop.framework.common.Constant;
import com.longtop.intelliweb.common.Log;

/**
 * 
 * @author IntelliWeb Team
 * @version 2.0
 */
public class SecurityFilter implements Filter {
	private Log log = Log.getLogger(SecurityFilter.class);
	private Set urls;
	private String logonUrl;
	private String encoding;

	public void init(FilterConfig config) throws ServletException {
		urls = new HashSet();
		String paramters = config.getInitParameter("unprotectedUrls");
		StringTokenizer st = new StringTokenizer(paramters, ",");
		while (st.hasMoreElements()) {
			urls.add(st.nextElement());
		}
		encoding = config.getInitParameter("encoding");
		this.logonUrl = config.getInitParameter("logonUrl");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		log.logDebug("..........doFilter............");
		if (encoding != null && !encoding.equals("")) {
			// 设置输出字符编码
			// response.setCharacterEncoding(encoding);
		}

		// 如果没有受保护的url，则直接返回
		if (isUnProtectedURL((HttpServletRequest) request)) {
			chain.doFilter(request, response);
			return;
		}

		// 如果是受保护的url，则需要判断是否已经过验证。如果没有经过验证，则转到登陆界面，重新登陆验证
		HttpSession session = ((HttpServletRequest) request).getSession(false);
		if (session == null || session.getAttribute(Constant.SESSION_OBJECT) == null) {
			request.getRequestDispatcher(logonUrl).forward(request, response);
		} else {
			chain.doFilter(request, response);
		}
	}

	/**
	 * isUnProtectedURL
	 * 
	 * @param request
	 *            ServletRequest
	 * @return boolean
	 */
	private boolean isUnProtectedURL(HttpServletRequest request) {

		String URL_Request = request.getServletPath();
		System.out.println("getServletPath:" + URL_Request);

		Iterator iterator = urls.iterator();
		while (iterator.hasNext()) {
			String str = (String) iterator.next();
			System.out.println(str);
		}

		return urls.contains(request.getServletPath());
	}

	public void destroy() {
	}
}
